package com.crl.game.simulation.server
{
	import com.crl.game.simulation.common.BaseSimulation;
	import com.crl.game.simulation.common.Performer;
	import com.crl.game.simulation.common.Router;
	import com.crl.game.simulation.common.SimulationObject;
	import com.crl.game.simulation.common.factory.SobFactory;
	import com.crl.game.simulation.common.manager.ScheduleManager;
	import com.crl.game.simulation.common.manager.SobManager;
	import com.crl.game.simulation.server.decoder.IServerRouter;
	import com.crl.game.simulation.server.state.UserControlState;
	import com.crl.manager.ITickable;
	import com.crl.manager.TickManager;
	import com.crl.net.SocketDelegate;
	import com.crl.net.transfer.Command;
	
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	
	/**
	 * 服务器环境 
	 * @author crl
	 * 
	 */	
	public class ServerSimulation extends BaseSimulation implements ITickable
	{
		private var socketServer:ServerSocket;
		
		private var ticker:TickManager;
		protected var router:IServerRouter;
		public function ServerSimulation()
		{
			super();
			
			ticker=new TickManager();
			ticker.add(this);
			
			defaults();

			socketServer=new ServerSocket();
			socketServer.bind(8886);
			socketServer.listen();
			socketServer.addEventListener(ServerSocketConnectEvent.CONNECT,onConnect);
		}
		
		protected function defaults():void{
			router=new Router(this);
			sobFactory=new SobFactory();
			actorManager=new SobManager();
			scheduleManager=new ScheduleManager();
		}
		
		
		private function onConnect(event:ServerSocketConnectEvent):void{
			var socket:Socket=event.socket;
			var client:Actor=sobFactory.create(1) as Actor;
			var socketDelegate:SocketDelegate=new SocketDelegate(socket);
			client.defaultControlState=new UserControlState(socketDelegate,router);
			
			attachUser(client);
		}
		
		override public function attachUser(performer:Performer):void{
			actorManager.set(performer.id,performer);
			scheduleManager.set(performer.id,performer);
		}
		
		override public function detachUser(performer:Performer):void{
			actorManager.set(performer.id,null);
			scheduleManager.set(performer.id,null);
		}
		
		
	  	public function receive(code:int,data:*,actorkey:int):void{
			var command:Command=new Command();
			command.code=code;
			command.data=data;
			var actor:Actor=actorManager.get(actorkey) as Actor;
			router.route(command,actor);
		}
		
	}
}